package com.chookss.login;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.chookss.HomeActivityss;
import com.chookss.HomeKnowledgeActivity;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.AppStatus;
import com.chookss.base.AppStatusManager;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.mine.set.ChangePassActivity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.RSACoder;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.UUidUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoConfig;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.old.SignUtils;
import com.chookss.view.ProtocolDialog;
import com.chookss.view.listener.SelectTwoDialogListener;
import com.gyf.immersionbar.ImmersionBar;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.johnrambo.ktea.net.http.RequestData;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SplashActivity extends AppCompatActivity {
    private MyHandler mHandler;
    private boolean isFirst = true; //第一次登录
    private RelativeLayout llContent;
    private LinearLayout llZhaofeng;
    private TextView tvCompany,tvZhaofengLogo;
    private ImageView ivLogo,ivZhaofengLogo;
    private String code = "0";
    private String errorMsg = "";//自动登录失败提示语
    private String ANDROID_ID = "";
    private int type = 0;//0正常 1被系统回收从新进入
    private boolean isFirstFlag=false;//是否首次登录

    private class MyHandler extends Handler {
        private final SoftReference<AppCompatActivity> softReference;

        public MyHandler(AppCompatActivity activity) {
            softReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case StaticClass.HANDLER_SPLASH:
                    if (isFirst) {
                        startActivity(new Intent(SplashActivity.this, GuideActivity.class));
                        finish();
                    } else {
                        if(isFirstFlag){
                            MyToast.show("首次登录，建议您重新设置密码");
                            Intent intent = new Intent(SplashActivity.this, ChangePassActivity.class);
                            intent.putExtra("type", "login");
                            startActivity(intent);
                        }else{
                            if (code.equals("200")) {
                                //正常登录成功
                                XJson.setLogFailure(SplashActivity.this,new ShareUtils().getString(SplashActivity.this,StaticClass.EMPLOYEECODE,""));
                                Intent intent = new Intent(SplashActivity.this, HomeActivityss.class);
                                intent.putExtra("isFirst", true);
                                startActivity(intent);
                                if ("T002".equals(new ShareUtils().getString(SplashActivity.this, StaticClass.THEME_CODE, ""))) {
                                    Intent intent2 = new Intent(SplashActivity.this, HomeKnowledgeActivity.class);
                                    intent2.putExtra("isFirst", true);
                                    startActivity(intent2);
                                }
                            }else  if (code.equals("4009")) {
                                //积分不足，请充值
                                Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                                intent.putExtra("errorMsg", getString(R.string.no_money));
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                                intent.putExtra("errorMsg", errorMsg);
                                startActivity(intent);
                            }
                        }
                        finish();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        initData();
    }

    public void initData() {
        type = getIntent().getIntExtra("type", 0);
        ImmersionBar.with(this)
                .transparentStatusBar() /*透明状态栏，不写默认透明色*/ /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(false)
                .flymeOSStatusBarFontColor(R.color.white) /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
        llContent = findViewById(R.id.llContent);
        tvCompany = findViewById(R.id.tvCompany);
        ivLogo = findViewById(R.id.ivLogo);
        if (getPackageName().equals("com.zhaofengnum")) {
            ivLogo.setBackgroundResource(R.drawable.zhaofeng_logo_bg);
        } else {
            ivLogo.setBackgroundResource(R.drawable.logo_bg);
        }
        if (getPackageName().equals("com.zhaofengnum")) {
            llZhaofeng.setVisibility(View.VISIBLE);
            ivLogo.setVisibility(View.GONE);
            ivZhaofengLogo.setBackgroundResource(R.mipmap.zhaofeng_logo);
            tvZhaofengLogo.setText(getResources().getString(R.string.app_name));
        } else {
            ivLogo.setBackgroundResource(R.drawable.logo_bg);
            //        llContent.setPadding(0,getNavigationHeight(this),0,0);
            String name = new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
            if (!Utils.isNull(name)&&tvCompany!=null) {
                tvCompany.setText(name);
            }
        }
        //获取版本号
        String versionName = Utils.getVersionName(this);
        RequestData.INSTANCE.setVersionName(versionName);
        Token.INSTANCE.setVersionName(versionName);
        mHandler = new MyHandler(this);
        isFirst = new ShareUtils().getBoolean(this, StaticClass.SHARE_IS_FIRST, true);
        AppStatusManager.getInstance().setAppStatus(AppStatus.STATUS_NORMAL);

        if (type == 1) {
            EventBus.getDefault().post(new MyEvent("HomeOver"));
            String token = Token.INSTANCE.getToken();
            if (!Utils.isNull(token)) {
                code = "200";
                Token.INSTANCE.setVersionName(Utils.getVersionName(SplashActivity.this));
                RequestData.INSTANCE.setToken(token);
                RequestData.INSTANCE.setVersionName(Utils.getVersionName(SplashActivity.this));
                MyApp.setAppSetting(token);
                OkGoConfig.init(MyApp.appCtx, token,
                        Utils.getVersionName(SplashActivity.this));
                getNavigations();
                XJson.setLogFailure(SplashActivity.this,new ShareUtils().getString(SplashActivity.this,StaticClass.EMPLOYEECODE,""));
            }
            mHandler.sendEmptyMessageDelayed(StaticClass.HANDLER_SPLASH, 1800);
        } else {
            if (isFirst) {
                new ProtocolDialog(this, new SelectTwoDialogListener() {
                    @Override
                    public void onCancel() {
                        MyApp.exitApp();
                        finish();
                    }

                    @Override
                    public void onSure() {
                        mHandler.sendEmptyMessageDelayed(StaticClass.HANDLER_SPLASH, 800);
                    }
                }).show();
            } else {
                login();
                mHandler.sendEmptyMessageDelayed(StaticClass.HANDLER_SPLASH, 2500);
            }
        }

    }

    private void login() {
        String companyName = new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
        String username = new ShareUtils().getString(this, StaticClass.USERNAME, "");
        String password = new ShareUtils().getString(this, StaticClass.ORIGINALPASS, "");
        if (!Utils.isNull(companyName) && !Utils.isNull(username) && !Utils.isNull(password)) {
            new ShareUtils().putBoolean(SplashActivity.this, StaticClass.ISLOGIN, true);
            if (!MyApp.mIsInitPUSHSuccess) {
                MyApp.initCloudChannel();
            }
        } else {
            String token = Token.INSTANCE.getToken();
            if (!Utils.isNull(token)) {
                new ShareUtils().putBoolean(SplashActivity.this, StaticClass.ISLOGIN, true);
                if (!MyApp.mIsInitPUSHSuccess) {
                    MyApp.initCloudChannel();
                }
                Token.INSTANCE.setVersionName(Utils.getVersionName(SplashActivity.this));
                RequestData.INSTANCE.setToken(token);
                RequestData.INSTANCE.setVersionName(Utils.getVersionName(SplashActivity.this));
                getNavigations();
            }
            return;
        }
        String deviceName = Build.BRAND + " " + Build.MODEL;
        ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        try {
            ANDROID_ID = UUidUtils.getCustomUUID(SplashActivity.this, ANDROID_ID);
            if(Utils.isNull(ANDROID_ID)){
                String id= new ShareUtils().getString(this, "local_id", "");
                if (Utils.isNull(id)) {
                    String uuid= UUID.randomUUID().toString();
                    ANDROID_ID=uuid;
                    new ShareUtils().putString(this, "local_id", uuid);
                }else{
                    ANDROID_ID=id;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (username.equals("13300000000")||username.equals("13503825592")) {
            ANDROID_ID = "27f6fd2ba9cfffff";
        }
        if (username.equals("13503825591")) {
            ANDROID_ID = "27f6fd2ba9c9521f";
        }
        if (username.equals("15713883582")) {
            ANDROID_ID = "27f6fd2ba9c9eee";
        }
        if (username.equals("18838825228")) {
            ANDROID_ID = "49883ae59107b892";
        }
        String encodePassword = RSACoder.encryRas(password);
        String encodeUsername = RSACoder.encryRas(username);
        String encodeDevice = RSACoder.encryRas(ANDROID_ID);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", companyName);
        map.put("username", username);
        map.put("password", password);
        map.put("type", "1");
        map.put("device", ANDROID_ID);
        map.put("deviceName", deviceName);
        String timeStamp = SignUtils.getTimeStamp();//20201208125238
        String nonce = SignUtils.getRandomString(14);
        String makeSignStr = SignUtils.makeSignStr(map, timeStamp, nonce, true);
        Map<String, String> maps = new HashMap<>();
        maps.put("companyName", companyName);
        maps.put("username", encodeUsername);
        maps.put("password", encodePassword);
        maps.put("type", "1");
        maps.put("device", encodeDevice);
        maps.put("deviceName", deviceName);
        maps.put("timestamp", timeStamp);
        maps.put("nonce", nonce);
        maps.put("sign", makeSignStr);
        MyHttpRequest.postRequest(Urls.login, this, maps, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body().toString());
                    code = jsonObject.getString("code");
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (data.has("theme")) {
                            //特殊纪念日 0主题变灰1正常
                            if("0".equals(data.getString("theme"))){
                                MyApp.THEME=true;
                            }else{
                                MyApp.THEME=false;
                            }
                        }
                        NavigationTools.saveUserData(SplashActivity.this,data,username,password);
                        if (data.getBoolean("flag")) {
                            isFirstFlag=true;
                        }

                    } else {
                        errorMsg = jsonObject.getString("msg");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    public void getNavigations() {
        Map<String,String> map=new HashMap<>();
        map.put("floorFlag","1");
        MyHttpRequest.getRequest(Urls.selectByRole, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    code = jsonObject.getString("code");
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (jsonArray.length() > 1) {
                            NavigationTools.setHomeBottomPermissions(SplashActivity.this,jsonArray);
                        }
                    }else{
                        errorMsg = jsonObject.getString("msg");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    private void getUUID() {

        login();
//        XXPermissions.with(this)
//                .permission(Permission.Group.STORAGE)
//                .request(new OnPermissionCallback() {
//                    @Override
//                    public void onGranted(List<String> granted, boolean all) {
//                        if (all) {
//                            ANDROID_ID = UUidUtils.getCustomUUID(SplashActivity.this, ANDROID_ID);
//                        }
//
//                    }
//
//                    @Override
//                    public void onDenied(List<String> denied, boolean quick) {
//                    }
//                });
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApp.isSplash = false;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

    }

    /**
     * 获取导航栏高度
     *
     * @param context
     * @return
     */
    public int getNavigationHeight(Context context) {
        int windowheight = getWindowManager().getDefaultDisplay().getHeight(); //获取无导航栏状态栏时窗口高度
        int fullheigh = 0;   //窗口总高度
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class klass;
        try {
            klass = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = klass.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            fullheigh = dm.heightPixels;  //获取窗口总高度
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (windowheight == fullheigh) return 0;   //无虚拟导航栏存在
        return fullheigh - windowheight - getStatusBarHeight(context);  //导航栏高度
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
}
